package com.rq.base.util;

import android.text.TextUtils;


import com.google.android.material.circularreveal.CircularRevealLinearLayout;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.rq.base.BASE.isDebug;

public class StringUtil {
    public static boolean isAllEmpty(String... con) {
        for (String s : con) {
            if (!TextUtils.isEmpty(s)) return false;
        }
        return true;
    }

    public static boolean isPhone(String num) {
        if (num == null) return false;
        Pattern pattern = Pattern.compile("^1\\d{10}$");
        return pattern.matcher(num).find();
    }

    public static String getTimeShowStr(long time) {
        return getTimeFormat(time, "yyyy-MM-dd HH:mm:ss");
    }

    public static String getNowTime(String type) {
        Date date = new Date();
        return getTimeFormat(date.getTime(), type);
    }

    public static String getTimeYDM(long time) {
        return getTimeFormat(time, "yyyy-MM-dd");
    }

    public static String getTimeFormat(long time, String pattern) {
        if (time > 0 && pattern != null) {
            DateFormat format = new SimpleDateFormat(pattern, Locale.CHINA);
            return format.format(new Date(time));
        }
        LOG.utilLog("错误调用，time不能小于0");
        return "";
    }

    public static String getShowPhone(String member_name) {
        if (!TextUtils.isEmpty(member_name)) {
            if (member_name.length() > 7) {
                return member_name.substring(0, 3) + "****" + member_name.substring(7);
            }
        }
        return "";
    }

    public static String getShowEmail(String mail) {
        try {
            int atIndex = mail.indexOf("@");
            int qianMian = (atIndex - 4 < 1) ? 1 : (atIndex - 4);
            int houMian = qianMian + 4 > atIndex ? atIndex : (qianMian + 4);
            return mail.substring(0, qianMian) + "****" + mail.substring(houMian);
        } catch (Exception e) {
        }
        return "";
    }

    public static boolean isUserAccountOk(String pass) {
        Pattern pattern = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$");
        return pattern.matcher(pass).find();
    }

    public static boolean isNameOk(String pass) {
        Pattern pattern = Pattern.compile("^^[\\u4E00-\\u9FA5]{2,4}$$");
        return pattern.matcher(pass).find();
    }

    //判断email格式是否正确
    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    public static boolean hasEmpty(String... con) {
        if (con == null || con.length == 0) return true;
        for (String s : con) {
            if (s == null || "".equals(s)) {
                return true;
            }
        }
        return false;
    }

    public static boolean hasCon(String... con) {
        if (con == null || con.length == 0) return false;
        for (String s : con) {
            if (!TextUtils.isEmpty(s)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isPassOk(String passwordStr) {
        if ("".equals(passwordStr) || passwordStr == null || passwordStr.length() < 8) {
            return false;
        }
        String regexZ = "[A-Z]+";
        String regexZ2 = "[a-z]+";
        String regexS = "[0-9]";
        String regexT = ".*[~!@#$%^&*.,\\-\\+].*";
        if (!Pattern.compile(regexZ).matcher(passwordStr).find()) {
            return false;
        }
        if (!Pattern.compile(regexZ2).matcher(passwordStr).find()) {
            return false;
        }
        if (!Pattern.compile(regexS).matcher(passwordStr).find()) {
            return false;
        }
        if (!Pattern.compile(regexT).matcher(passwordStr).find()) {
            return false;
        }
        return true;
    }

    public static String gstNumFromStr(String str) {
        String regEx = "\\d*\\..?\\d*";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.group(0);
    }

    private static Pattern PAT_HAS_END_EMPTY = Pattern.compile("[\\s\t\r\n]*$");
    private static Pattern PAT_HAS_EMPTY = Pattern.compile("\\s*|\t|\r|\n");
    private static Pattern PAT_IS_PHONE = Pattern.compile("^1\\d{10}$");
    private static Pattern PAT_IS_6_16_STR = Pattern
            .compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$");
    private static Pattern PAT_IS_EMAIL = Pattern
            .compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
    private static Pattern PAT_IS_IP = Pattern
            .compile("([1-9]|[1-9]\\d|1\\d{2}|2[0-1]\\d|22[0-3])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}");

    private static Pattern MONEY1 = Pattern.compile("(\\d+\\.\\d+)E(\\d*)");
    private static Pattern MONEY2 = Pattern.compile("(\\D*)(\\d+\\.\\d+)E(\\d*)");
    private static Pattern TIMESTAMP = Pattern.compile("(\\d{13})");
    private static Pattern TIMESTAMP_2 = Pattern.compile("(\\d{10})");

    //time stamp
    public static int getShowLength(String string) {
        if (string == null) {
            return 0;
        }
        String newString = null;
        try {
            newString = new String(string.getBytes("GB2312"), StandardCharsets.ISO_8859_1);
            return newString.length();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return string.length();
        }
    }

    public static long date2TimeStamp(String date_str, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.parse(date_str).getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static int getLength(String c) {
        char[] allC = c.toCharArray();
        int length = 0;
        for (int i = 0; i < allC.length; i++) {
            if ((allC[i] >= 0x4e00) && (allC[i] <= 0x9fbb)) {
                length += 3;
            } else {
                length++;
            }
        }
        return length;
        //    1.方法一 char c = 'a'; if((c >= 0x4e00)&&(c <= 0x9fbb)) { System.out.println("是中文&qu
    }


    public static String removeEndEmptyStr(CharSequence str) {
        String dest = null;
        if (str == null) {
            return dest;
        } else {
            Matcher m = PAT_HAS_END_EMPTY.matcher(str);
            dest = m.replaceAll("");
            return dest;
        }
    }

    /**
     * 判断某个字符串是否是一个 IP 地址
     */
    public static boolean isIP(String ip) {
        Matcher matcher = PAT_IS_IP.matcher(ip);
        return matcher.matches();
    }

    public static String removeAllEmptyStr(CharSequence str) {
        String dest = "";
        if (str == null) {
            return dest;
        } else {
            Matcher m = PAT_HAS_EMPTY.matcher(str);
            dest = m.replaceAll("");
            return dest;
        }
    }

    public static boolean equals(CharSequence a, CharSequence b) {
        return TextUtils.equals(StringUtil.removeEndEmptyStr(a), StringUtil.removeEndEmptyStr(b));
    }

    public static String getTime(long calendar) {
        return formatter.format(calendar);
    }

    public static String getUploadTime(Calendar calendar) {
        return formatter.format(calendar.getTimeInMillis());
    }

    public static String FMD = "yyyy-MM-dd";
    public final static String TIME = "yyyy-MM-dd HH:mm:ss";
    static SimpleDateFormat formatter = new SimpleDateFormat(TIME);

    public static String addWithDays(String origin, int add) {
        Calendar now = Calendar.getInstance();
        formater(origin, now);
        now.add(Calendar.DAY_OF_MONTH, add);
        return formatter.format(now.getTimeInMillis());
    }

    private static void formater(String origin, Calendar now) {
        try {
            Date time = formatter.parse(origin);
            now.setTime(time);
        } catch (ParseException e) {
            e.printStackTrace();
            try {
                String con[] = origin.split("[ /:]");
                now.set(Integer.parseInt(con[0]), Integer.parseInt(con[1]) - 1, Integer.parseInt(con[2]));
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    //
//    /**
//     * 6~16 位包含 数字字母密码
//     *
//     * @return
//     */
//    public static boolean isUserAccountOk(String pass) {
//        return PAT_IS_6_16_STR.matcher(pass).find();
//    }
//
//    public static boolean isNameOk(String pass) {
//        Pattern pattern = Pattern.compile("^^[\\u4E00-\\u9FA5]{2,4}$$");
//        return pattern.matcher(pass).find();
//    }
//
//    //判断email格式是否正确
//    public static boolean isEmail(String email) {
//        Matcher m = PAT_IS_EMAIL.matcher(email);
//        return m.matches();
//    }
//
//    public static boolean hasEmpty(String... con) {
//        if (con == null || con.length == 0) {
//            return true;
//        }
//        for (String s : con) {
//            if (s == null || "".equals(s) || "".equals(s.trim())) {
//                return true;
//            }
//        }
//        return false;
//    }
    public static String getNum2Dot(double money) {
        return getNumAfterDot(money, 2);
    }

    public static String getNumAfterDot(double money, int numberAfterDot) {
        try {
            return getNumAfterDot4(new BigDecimal(money).setScale(numberAfterDot, RoundingMode.HALF_UP).toString());
        } catch (Exception e) {
            LOG.e("StringUtil", "getNumAfterDot.307:");
            return "0";
        }
    }

    public static String getNumAfterDot4(double money) {
        return getNumAfterDot(money, 4);
    }

    private static Pattern MONEY = Pattern.compile("(\\d+\\.\\d{4})(\\d+)");

    public static String getNumAfterDot(CharSequence str, int numberAfterDot) {
        if (str == null) return "";
        Matcher m3 = MONEY2.matcher(str);
        String res = String.valueOf(str);
        if (m3.find()) {
            res = m3.group(1) + new BigDecimal(m3.group(2))
                    .multiply(new BigDecimal(Math.pow(10D, Double.parseDouble(m3.group(3)))))
                    .setScale(numberAfterDot, RoundingMode.HALF_UP).toString();
        } else if (MONEY1.matcher(str).find()) {
            res = new BigDecimal(m3.group(1))
                    .multiply(new BigDecimal(Math.pow(10D, Double.parseDouble(m3.group(2)))))
                    .setScale(numberAfterDot, RoundingMode.HALF_UP).toString();
        } else {
            Pattern MONEY = Pattern.compile("(\\d+\\.\\d{" + numberAfterDot + "})(\\d+)");
            Matcher m = MONEY.matcher(str);
            if (m.find() && m.groupCount() > 1) {
                res = m.group(1);
            }
        }
        if (res.indexOf(".") == res.length() - 2 && res.indexOf(".") > 0) {
            return res + "0";
        }
        return res;
    }

    public static String getNumAfterDot4(CharSequence str) {
        try {

            if (str == null) return "";
            Matcher m3 = MONEY2.matcher(str);
            String res = String.valueOf(str);
            if (m3.find()) {
                res = m3.group(1) + new BigDecimal(m3.group(2))
                        .multiply(new BigDecimal(Math.pow(10D, Double.parseDouble(m3.group(3)))))
                        .setScale(4, RoundingMode.HALF_UP).toString();
            } else if (MONEY1.matcher(str).find()) {
                res = new BigDecimal(m3.group(1))
                        .multiply(new BigDecimal(Math.pow(10D, Double.parseDouble(m3.group(2)))))
                        .setScale(4, RoundingMode.HALF_UP).toString();
            } else {
                Matcher m = MONEY.matcher(str);
                if (m.find() && m.groupCount() > 1) {
                    res = m.group(1);
                }
            }
            if (res.indexOf(".") == res.length() - 2 && res.indexOf(".") > 0) {
                return res + "0";
            }
            return res;
        } catch (Exception e) {
            return "0.0000";
        }
    }

    public static String getKwShow(double dlA, double dyV) {
        String gongLv;
        if (StringUtil.multiplyDouble(dlA, dyV) > 1_0000_000) {
            gongLv = StringUtil.divide(StringUtil.multiply(dlA, dyV), "10000000") + "万kw";
        } else if (StringUtil.multiplyDouble(dlA, dyV) > 1_000) {
            gongLv = StringUtil.divide(StringUtil.multiply(dlA, dyV), "1000") + "kw";
        } else {
            gongLv = StringUtil.multiply(dlA, dyV) + "w";
        }
        return gongLv;
    }

    public static String divide(String money, String money2) {
        try {
            return new BigDecimal(money).divide(new BigDecimal(money2), 2, RoundingMode.HALF_UP)
                    .toString();
        } catch (Exception e) {
            return "0.00";
        }
    }

    public static String divideRate(String money, String money2) {
        try {
            return new BigDecimal(money).multiply(new BigDecimal(100D)).divide(new BigDecimal(money2), 2, RoundingMode.HALF_UP)
                    .toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "0.00";
        }
    }

    public static String multiply(String money, String money2) {
        try {
            return new BigDecimal(money).multiply(new BigDecimal(money2))
                    .setScale(2, RoundingMode.HALF_UP).toString();
        } catch (Exception e) {
            return "0.00";
        }
    }

    public static String multiply(double money, double money2) {
        try {
            return new BigDecimal(money).multiply(new BigDecimal(money2))
                    .setScale(2, RoundingMode.HALF_UP).toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "0.00";
        }
    }

    public static double multiplyDouble(double money, double money2) {
        try {
            return new BigDecimal(money).multiply(new BigDecimal(money2))
                    .setScale(2, RoundingMode.HALF_UP).doubleValue();
        } catch (Exception e) {
            e.printStackTrace();
            return 0D;
        }
    }

    public static String getNum2Dot(String money) {
        try {
            return new BigDecimal(money).setScale(2, RoundingMode.HALF_UP).toString();
        } catch (Exception e) {
            return "0.00";
        }
    }

    public static BigDecimal getMoneyDouble(String money) {
        try {
            return new BigDecimal(money).setScale(2, RoundingMode.HALF_UP);
        } catch (Exception e) {
            return new BigDecimal("0.00");
        }
    }

    //  public static BigDecimal getMoneyDouble(String money, String money2) {
    //    try {
    //      return new BigDecimal(money).multiply(new BigDecimal(money2))
    //                                  .setScale(2, RoundingMode.HALF_UP);
    //    } catch (Exception e) {
    //      return new BigDecimal("0.00");
    //    }
    //  }

    public static String getUploadStr(Set<String> keys) {
        if (keys == null) {
            return "";
        }
        String or = keys.toString();
        if (or.length() > 2) {
            return or.substring(1, or.length() - 1).replaceAll(" ", "");
        }
        return "";
    }

    public static double add(double allDebit, String debitcz) {
        try {
            return new BigDecimal(debitcz).add(new BigDecimal(allDebit)).setScale(2, RoundingMode.HALF_UP)
                    .doubleValue();
        } catch (Exception e) {
            return allDebit;
        }
    }

    public static String add(CharSequence allDebit, CharSequence debitcz) {
        try {
            return new BigDecimal(String.valueOf(debitcz)).add(new BigDecimal(String.valueOf(allDebit)))
                    .setScale(2, RoundingMode.HALF_UP).toString();
        } catch (Exception e) {
            return String.valueOf(allDebit);
        }
    }


    static SimpleDateFormat show = new SimpleDateFormat("yyyy/MM/dd");

    public static String getShowTime(long calendar) {
        return show.format(calendar);
    }

    public static String getShowTime(Calendar calendar) {
        return show.format(calendar.getTimeInMillis());
    }

    //\\/Date(1638460800000)\\/
    public static String getTimeFromNet(String str) {
        try {
            Matcher matcher1 = TIMESTAMP.matcher(str);
            if (matcher1.find()) {
                return formatter.format(Long.parseLong(matcher1.group(0)));
            }
            Matcher matcher2 = TIMESTAMP_2.matcher(str);
            if (matcher2.find()) {//短时间戳
                return formatter.format(Long.parseLong(matcher2.group(0)) * 1000);
            }
            String[] nums = str.split("\\D");
            if (nums.length == 6) {
                return nums[0] + "-" + nums[1] + "-" + nums[2];
            }
            Matcher m = TIMESTAMP.matcher(str);
            if (m.find()) {
                String res = m.group(0);
                LOG.e("StringUtil", str + ".getTimeFromNet.324:" + m.groupCount());
                return formatter.format(Long.parseLong(res));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        LOG.e("StringUtil", "getTimeFromNet.321:");
        return str;
    }

    public static Long getTimeLongFromNet(String str) {
        try {
            if (str == null) return 0L;
            String[] nums = str.split("\\D");
            if (nums.length == 6) {
                if (isDebug())
                    for (int i = 0; i < nums.length; i++) {
                        LOG.e("StringUtil", str + "." + i + ":" + nums[i]);
                    }
                Calendar now = Calendar.getInstance();
                now.set(Integer.parseInt(nums[0]), Integer.parseInt(nums[1]) - 1, Integer
                        .parseInt(nums[2]), Integer.parseInt(nums[3]), Integer.parseInt(nums[4]), Integer
                        .parseInt(nums[5]));
                return now.getTimeInMillis();
            }
            Matcher m = TIMESTAMP.matcher(str);
            if (m.find()) {
                String res = m.group(0);
                LOG.e("StringUtil", str + ".getTimeFromNet.324:" + m.groupCount());
                return Long.parseLong(res);
            }
        } catch (Exception e) {
        }
        return 0L;
    }

    public static String getRate(float v) {
        return getNumAfterDot(v, 2);
    }

    public static String getKeepTime(long using) {
        using = using / 1000;
        if (using < 60) {
            return using + " s";
        } else if (using < 3600) {
            return (using / 60) + "m" + (using % 60 == 0 ? "" : (using % 60 + "s"));
        } else if (using < 3600 * 24) {
            return using / 3600 + "h" + (using % 3600 / 60) + "m";
        } else {
            return using / (3600 * 24) + "d" + (using % (3600 * 24) / 3600) + "h";
        }
    }

    public static boolean isToday(long time) {
        return isSameDay(time, System.currentTimeMillis());
    }

    public static boolean isSameDay(long time, long time2) {
        Calendar today = Calendar.getInstance();
        today.setTimeInMillis(time2);
        Calendar target = Calendar.getInstance();
        target.setTimeInMillis(time);
        return today.get(Calendar.YEAR) == target.get(Calendar.YEAR)
                && today.get(Calendar.MONTH) == target.get(Calendar.MONTH)
                && today.get(Calendar.DAY_OF_MONTH) == target.get(Calendar.DAY_OF_MONTH);
    }

    public static boolean more7Days(long time) {

        Calendar target = Calendar.getInstance();
        target.setTimeInMillis(time);
        boolean res = System.currentTimeMillis() - time > 7 * 24 * 3600 * 1000;
        LOG.e("StringUtil", "more7Days.542:" + getShowTime(time));
        LOG.e("StringUtil", "more7Days.543:" + getShowTime(System.currentTimeMillis()));
        LOG.e("StringUtil", "more7Days.546:" + res);
        return res;
    }
}
